package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.dao.NoticeDao;
import com.book.dto.NoticePage;
import com.book.entity.Notice;
import com.book.service.NoticeService;
import com.book.utils.ResponseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
//本service错误码7001.开始
@Service
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    private NoticeDao noticeDao;

    @Override
    public ResponseResult selectList(NoticePage noticePage) {
        try {
            PageHelper.startPage(noticePage.getCurrentPage(),noticePage.getPageSize());
            QueryWrapper<Notice> qw = new QueryWrapper<>();
            qw.like("title",noticePage.getMessage()).or().like("content",noticePage.getMessage());
            qw.orderByDesc("id");
            List<Notice> noticeList = noticeDao.selectList(qw);
            PageInfo<Notice> noticePageInfo = new PageInfo<>(noticeList);

            if(noticePage.getCurrentPage()>noticePageInfo.getPages()){
                PageHelper.startPage(noticePageInfo.getPages(),noticePage.getPageSize());
                noticeList = noticeDao.selectList(qw);
                noticePageInfo = new PageInfo<>(noticeList);
            }
//            System.out.println(noticePageInfo);
            return new ResponseResult(200,"查询成功",noticePageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(7001,"查看公告失败!!");
        }
    }

    @Override
    public ResponseResult delete(int id) {
        try {
            noticeDao.deleteById(id);
            return new ResponseResult(200,"删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(7002,"删除失败!!");
        }
    }

    @Override
    public ResponseResult getNotice(int id) {
        try {
            return new ResponseResult(200,"获取公告成功",noticeDao.selectById(id));
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(7003,"获取公告失败!!");
        }
    }


    /**
     * 编辑或添加公告，主要看公告id是不是为0,为0则为添加
     * @param notice
     * @return
     */
    @Override
    public ResponseResult noticeSave(Notice notice) {
        try {
            notice.setTime(new Date());
            if(notice.getId() == 0){
                noticeDao.insert(notice);
            }else {
                noticeDao.updateById(notice);
            }
            return new ResponseResult(200,"保存成功成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(7004,"保存失败!!");
        }
    }
}
